<template>
  <a-layout>
    <a-layout-content
        :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '680px' }"
    >
      <p>
        <a-form :model="nameParam" layout="inline">
          <a-form-item>
            <a-input v-model:value="nameParam.name" placeholder="输入要搜索的名称"
                     size="large" @keyup.enter="handleQuery({page:1,size:pagination.pageSize,name:nameParam.name})">
            </a-input>
          </a-form-item>
          <a-form-item>
            <a-button size="large" type="primary"
                      @click="handleQuery({page:1,size:pagination.pageSize,name:nameParam.name})">搜索电子书
            </a-button>
          </a-form-item>
          <a-form-item>
            <a-button size="large" type="primary" @click="add">新增电子书</a-button>
          </a-form-item>
        </a-form>
      </p>
      <a-table
          :columns="columns"
          :data-source="ebooks"
          :loading="loading"
          :pagination="pagination"
          :row-key="record => record.id"
          @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'cover'">
            <a>
              <a-avatar :src="record.cover"/>
            </a>
          </template>
          <template v-if="column.key === 'category'">
            <span>{{ getCategoryNameById(record.category1Id) }}/{{ getCategoryNameById(record.category2Id) }}</span>
          </template>
          <template v-else-if="column.key === 'action'">
            <span>
              <a-space size="small">
                <router-link :to="'/admin/doc?ebookId='+record.id">
                  <a-button type="primary">文档管理</a-button>
                </router-link>
                <a-button type="primary" @click="edit(record)">编辑</a-button>
                <a-popconfirm
                    cancel-text="否"
                    ok-text="是"
                    title="删除后不可恢复，确认删除?"
                    @confirm="handleDelete(record.id)"
                >
                  <a-button danger type="primary">删除</a-button>
                </a-popconfirm>
              </a-space>
            </span>
          </template>
        </template>
      </a-table>
    </a-layout-content>
  </a-layout>
  <a-modal
      v-model:visible="visible"
      :confirm-loading="confirmLoading"
      :ok-text=okText
      cancel-text="取消"
      title="电子书表单"
      @ok="handleOk"
  >
    <a-form :label-col="{ span: 6 }" :model="ebook">
      <a-form-item label="封面">
        <a-upload
            v-model:file-list="fileList"
            :action="serverAddr+'/ebook/upload/cover'"
            :before-upload="beforeUpload"
            :show-upload-list="false"
            accept="image/png, image/jpeg,image/gif"
            class="avatar-uploader"
            list-type="picture-card"
            name="file"
            @change="handleCoverChange"
        >
          <div v-if="ebook.cover">
            <img :src="ebook.cover" alt="cover" class="uploadImg"/>
          </div>
          <div v-else>
            <loading-outlined v-if="loading"></loading-outlined>
            <plus-outlined v-else></plus-outlined>
            <div class="ant-upload-text">点击上传</div>
          </div>
        </a-upload>
        <p v-if="ebook.cover">点击可修改封面</p>
      </a-form-item>
      <a-form-item label="名称">
        <a-input v-model:value="ebook.name"/>
      </a-form-item>
      <a-form-item label="分类">
        <a-cascader v-model:value="categorysIds"
                    :field-names="{label:'name',value:'id',children:'children'}"
                    :options="level1"/>
      </a-form-item>
      <a-form-item label="描述">
        <a-textarea
            v-model:value="ebook.description"
            :auto-size="{ minRows: 3, maxRows: 5 }"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script lang="ts">
import {defineComponent, onMounted, ref} from 'vue';
import axios from "axios";
import {message} from "ant-design-vue";
import {Tool} from "@/util/tool";
import {LoadingOutlined, PlusOutlined} from '@ant-design/icons-vue';

export default defineComponent({
  name: 'AdminEbook',
  components: {
    LoadingOutlined,
    PlusOutlined
  },
  setup() {
    const coveloading = ref<boolean>(false);
    const categorysIds = ref();
    const ebooks = ref();
    const ebook = ref();
    const nameParam = ref({name: ''});
    const pagination = ref({
      total: 0,
      current: 1,
      pageSize: 2
    });

    const loading = ref(false);
    const fileList = ref();
    const serverAddr = ref(process.env.VUE_APP_SERVER);

    const columns = [
      {
        title: '封面',
        dataIndex: 'cover',
        key: 'cover'
      },
      {
        title: '名称',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '分类',
        dataIndex: 'category',
        key: 'category',
      },
      {
        title: '描述',
        dataIndex: 'description',
        key: 'description',
        width: 400
      },
      {
        title: '文档数',
        dataIndex: 'docCount',
        key: 'docCount'
      },
      {
        title: '阅读数',
        dataIndex: 'viewCount',
        key: 'viewCount'
      },
      {
        title: '点赞数',
        dataIndex: 'voteCount',
        key: 'voteCount'
      },
      {
        title: 'Action',
        dataIndex: 'action',
        key: 'action'
      }
    ];

    /**
     * 数据查询
     */
    const handleQuery = (params: any) => {
      loading.value = true;
      axios.get("/ebook/list", {
        params: {
          page: params.page,
          size: params.size,
          name: params.name
        }
      }).then((response) => {
        loading.value = false;
        const data = response.data;
        if (data.success) {
          ebooks.value = data.content.list;

          //重置分页按钮
          pagination.value.current = params.page;
          pagination.value.total = data.content.total;//有这个参数，前端才能计算出一共分成几页
        } else {
          message.error(data.message);
        }
      })
    }

    /**
     * 表格点击页码时触发
     */
    const handleTableChange = (pagination: any) => {
      handleQuery({
        page: pagination.current,
        size: pagination.pageSize,
        name: nameParam.value.name
      })
    }

    const visible = ref<boolean>(false);
    const confirmLoading = ref<boolean>(false);
    const okText = ref();

    /**
     * 编辑
     * @param record
     */
    const edit = (record: any) => {
      okText.value = "修改";
      visible.value = true;
      //复制一个新对象，这样进行编辑的时候，就不会修改表格数据了
      //ebook.value = record，这样写就和表格数据绑定了
      ebook.value = Tool.copy(record);
      categorysIds.value = [ebook.value.category1Id || "", ebook.value.category2Id || ""];
    }

    /**
     * 新增
     */
    const add = () => {
      okText.value = "新增";
      visible.value = true;
      categorysIds.value = [];
      ebook.value = {};
    }

    const handleDelete = (id: any) => {
      axios.delete("/ebook/delete/" + id).then((response) => {
        const data = response.data;
        if (data.success) {
          //重新加载列表
          handleQuery({
            page: pagination.value.current,
            size: pagination.value.pageSize
          })

          message.success("删除成功");
        }
      })
    }

    const handleOk = () => {
      confirmLoading.value = true;
      ebook.value.category1Id = categorysIds.value[0];
      ebook.value.category2Id = categorysIds.value[1];
      axios.post("/ebook/save", ebook.value).then((response) => {
        confirmLoading.value = false;
        const data = response.data;
        if (data.success) {
          visible.value = false;

          //重新加载列表
          handleQuery({
            page: pagination.value.current,
            size: pagination.value.pageSize
          })

          message.success(okText.value + "成功");
        } else {
          message.error(data.message);
        }
      }).catch(e => {
        confirmLoading.value = false;
        message.error(e.message);
      })
    }

    const level1 = ref();//树形结构
    let categorys: any;
    categorys = [];

    /**
     * 数据查询
     */
    const handleQueryCategory = () => {
      loading.value = true;
      axios.get("/category/all").then((response) => {
        loading.value = false;
        const data = response.data;
        categorys = data.content;
        if (data.success) {
          level1.value = [];
          level1.value = Tool.array2Tree(data.content, 0);

          //查询电子书
          handleQuery({
            page: 1,
            size: pagination.value.pageSize
          })
        } else {
          message.error(data.message);
        }
      })
    }

    const getCategoryNameById = (cid: number) => {
      let result = "";
      categorys.forEach((c: any) => {
        if (c.id === cid) {
          result = c.name;
        }
      });
      return result;
    };

    const handleCoverChange = (info: any) => {
      if (info.file.status === 'uploading') {
        loading.value = true;
        return;
      }
      if (info.file.status === 'done') {
        loading.value = false;
        ebook.value.cover = info.file.response.content;
        message.success("上传成功");
      }
      if (info.file.status === 'error') {
        loading.value = false;
        message.error('上传失败');
      }
    };

    const beforeUpload = (file: any) => {
      const isImg = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
      if (!isImg) {
        message.error('只允许上传图片!');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        message.error('图片大小不允许超过2MB!');
      }
      return isImg && isLt2M;
    };

    onMounted(() => {
      //查询分类
      handleQueryCategory();
    })

    return {
      ebooks,
      columns,
      pagination,
      loading,
      handleTableChange,
      visible,
      confirmLoading,
      edit,
      handleOk,
      ebook,
      add,
      okText,
      handleDelete,
      nameParam,
      handleQuery,
      categorysIds,
      level1,
      getCategoryNameById,
      coveloading,
      handleCoverChange,
      beforeUpload,
      fileList,
      serverAddr
    };
  }
});
</script>
<style scoped>
.ant-avatar {
  width: 50px;
  height: 50px;
  line-height: 50px;
  border-radius: 8%;
  margin: 5px 0;
}

.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.uploadImg {
  width: 100%;
  height: 100%;
}
</style>
